package com.cf.web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.cf.dao.UserDao;
import com.cf.dao.entity.User;
import com.cf.dao.entity.session;
import com.cf.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
@WebServlet("/getSessionUser")
public class GetSessionUserServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();
        private session sessions = new session();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取 Session

        // 从 session 中获取存储的用户信息
        int userId = sessions.getUserid();
        System.out.println(userId);
        User user = null;
        // 创建返回的 JSON 对象
        JSONObject result = new JSONObject();

        if (userId != 0) {
            // 如果用户 ID 存在，查询数据库获取用户信息
            try {
                user = userDao.selectUserById(userId);
                if (user != null) {
                    result.put("success", true);
                    result.put("user", new JSONObject()
                            .fluentPut("id", user.getId())
                            .fluentPut("name", user.getName())
                            .fluentPut("email", user.getEmail())
                            .fluentPut("avatar", user.getAvatar())
                            .fluentPut("sexy", user.getSexy())
                            .fluentPut("age", user.getAge())
                            .fluentPut("phone", user.getPhone())
                            .fluentPut("state", user.getState())
                            .fluentPut("account", user.getAccount())
                            .fluentPut("commentall", user.getCommentall())
                    );
                }
            } catch (SQLException e) {
                result.put("success", false);
                result.put("message", "数据库错误");
            }
        }

        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(result.toJSONString());
    }
}
